/*
 * 人人信用管理有限公司版权所有.
 * 
 * @Description:
 * 
 * @author: liyuliang
 * 
 * @date: 20 Apr 2017 10:44:16 am
 * 
 * 注意：本内容仅限于人人信用管理有限公司内部传阅，禁止外泄以及用于其他的商业目的.
 */

package com.rrx360.common.util;

import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class FirstLetterUtil {

  private static Logger logger = LogManager.getLogger(FirstLetterUtil.class);

  public static final char NONE = '0';

  private static int BEGIN = 45217;
  private static int END = 63486;
  private static char[] chartable = {'啊', '芭', '擦', '搭', '蛾', '发', '噶', '哈', '哈', '击', '喀', '垃',
      '妈', '拿', '哦', '啪', '期', '然', '撒', '塌', '塌', '塌', '挖', '昔', '压', '匝',};
  private static int[] table = new int[27];
  private static char[] initialtable = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'H', 'J', 'K', 'L',
      'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'T', 'T', 'W', 'X', 'Y', 'Z',};

  static {
    for (int i = 0; i < 26; i++) {
      table[i] = gbValue(chartable[i]);
    }
    table[26] = END;
  }

  static Map<Character, Character> map = new ConcurrentHashMap<>();

  /**
   */
  public static String getFirstLetter(String sourceStr) {
    StringBuilder builder = new StringBuilder();
    String str = sourceStr.toLowerCase(Locale.getDefault());
    int strLength = str.length();
    int i;
    for (i = 0; i < strLength; i++) {
      builder.append(getFirstLetter(str.charAt(i)));
    }
    return builder.toString();
  }

  /**
   */
  public static char getFirstLetter(Character ch) {
    if (ch == null) {
      return NONE;
    }
    Character value = map.get(ch);
    if (value != null) {
      return value;
    }
    value = getFirstLetter(ch);
    map.put(ch, value);
    return value;
  }

  private static char getFirstLetter(char ch) {
    // 对英文字母的处理：小写字母转换为大写，大写的直接返回
    if (ch >= 'a' && ch <= 'z') {
      return Character.toUpperCase(ch);
    }
    if (ch >= 'A' && ch <= 'Z') {

      return ch;
    }
    int gb = gbValue(ch);

    if ((gb < BEGIN) || (gb > END)) {
      return NONE;
    }

    int i;
    for (i = 0; i < 26; i++) {
      if ((gb >= table[i]) && (gb < table[i + 1])) {
        break;
      }
    }

    if (gb == END) {
      i = 25;
    }
    return initialtable[i];
  }

  private static int gbValue(char ch) {
    String str = "";
    str += ch;
    try {
      byte[] bytes = str.getBytes("GB2312");
      if (bytes.length < 2) {
        return 0;
      }
      return (bytes[0] << 8 & 0xff00) + (bytes[1] & 0xff);
    } catch (Exception e) {
      return 0;
    }
  }

  public static void main(String[] args) {
    System.out.println(getFirstLetter("中话李玉兰aZ12@!"));
  }
}
